package com.socialuni.center.web.serive;

import com.socialuni.center.web.factory.CenterMineUserDetailROFactory;
import com.socialuni.center.web.model.DO.user.IdCardDO;
import com.socialuni.center.web.model.DO.user.UserDetailDO;
import com.socialuni.center.web.model.RO.user.CenterMineUserDetailRO;
import com.socialuni.center.web.repository.IdCardRepository;
import com.socialuni.center.web.repository.shell.VipSaleRepository;
import com.socialuni.center.web.repository.user.UserDetailRepository;
import com.socialuni.center.web.user.userManage.CenterUserCheck;
import com.socialuni.center.web.utils.CenterUserUtil;
import com.socialuni.sdk.constant.AppConfigConst;
import com.socialuni.sdk.constant.CommonConst;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.model.UserEditVO;
import com.socialuni.sdk.repository.ChatRepository;
import com.socialuni.sdk.repository.ChatUserRepository;
import com.socialuni.sdk.repository.UserImgRepository;
import com.socialuni.sdk.repository.UserRepository;
import com.socialuni.sdk.service.comment.IllegalWordService;
import com.socialuni.sdk.utils.GenderUtil;
import com.socialuni.sdk.utils.common.BirthdayAgeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
public class UserService {
    @Resource
    private UserRepository userRepository;
    @Resource
    private EntityManager entityManager;
    @Resource
    private UserImgRepository userImgRepository;
    @Resource
    private IdCardRepository idCardRepository;
    @Resource
    private VipSaleRepository vipSaleRepository;
    @Resource
    private IllegalWordService illegalWordService;
    @Value("${config.initAvatar}")
    private String initAvatar;
    @Resource
    private FollowService followService;
    @Resource
    private UserDetailRepository userDetailRepository;
    @Resource
    private VipService vipService;
    @Resource
    private ChatRepository chatRepository;
    @Resource
    private ChatUserRepository chatUserRepository;

    @Resource
    private CenterUserCheck centerUserCheck;


    public void oldVersionCompatible(UserEditVO userEditVO) {

        //性别旧版本兼容
        String editGender = GenderUtil.getUserEditGenderByOldGender(userEditVO.getGender());
        userEditVO.setGender(editGender);
        //城市旧版本兼容

        String city = userEditVO.getCity();
        if (StringUtils.isEmpty(city)) {
            userEditVO.setCity(userEditVO.getLocation());
        }
    }

    @Transactional
    public CenterMineUserDetailRO editUser(UserEditVO userEditVO) {

        //旧版本兼容
        this.oldVersionCompatible(userEditVO);


        UserDO mineUser = CenterUserUtil.getMineUser();
        //昵称
        String nickname = userEditVO.getNickname();
        centerUserCheck.checkUserNickname(nickname, mineUser);

        String editGender = GenderUtil.getUserEditGenderByOldGender(userEditVO.getGender());
        GenderUtil.checkUserEditGenderType(editGender);
        mineUser.setGender(editGender);

        /*if (!user.getGender().equals(editGender)) {
            //如果性别修改过，则不可再修改
            if (user.getGenderModified()) {
                throw new SocialBusinessException("用户已修改过性别，不可再次修改，" + ErrorMsg.CONTACT_SERVICE);
            }
            user.setGenderModified(true);
        }*/

        //生日，年龄
        String birthday = userEditVO.getBirthday();
        if (StringUtils.isNotEmpty(birthday)) {
            mineUser.setBirthday(birthday);
            mineUser.setAge(BirthdayAgeUtil.getAgeByBirth(birthday));
        }
        centerUserCheck.checkUserCity(userEditVO.getCity(), mineUser);

        UserDetailDO userDetailDO = CenterUserUtil.getUserDetail(mineUser);
        centerUserCheck.checkUserContactAccount(userEditVO, userDetailDO);
        userDetailRepository.save(userDetailDO);
        mineUser.setUpdateTime(new Date());
        userRepository.save(mineUser);

        CenterMineUserDetailRO centerMineUserDetailRO = CenterMineUserDetailROFactory.editUserGetMineUserDetail(mineUser, userDetailDO);

        return centerMineUserDetailRO;
    }


    public UserDO addIdCard(UserDO user, IdCardDO idCardDO) {
        //首先将之前的所有idcard改为禁用，目前不存在多次认证的情况
        /*List<IdCardDO> idCardDOS = idCardRepository.findByUserAndStatus(user, CommonStatus.enable);
        for (IdCardDO cardDO : idCardDOS) {
            cardDO.setStatus(CommonStatus.disable);
        }
        idCardRepository.saveAll(idCardDOS);*/
        // 新idcard信息
        idCardDO.setUserId(user.getId());
        idCardRepository.save(idCardDO);
        // 用户身份证状态改为审核中状态
//        user.setIdCardStatus(ReportStatus.audit);
        user.setUpdateTime(new Date());
        //提交认证，更新颜值分
        this.updateFaceContent(user);
        userRepository.save(user);
        entityManager.clear();
        return userRepository.getOne(user.getId());
    }


    //更新用户颜值相关内容
    public void updateUserListFaceContent(List<UserDO> users) {
        for (UserDO user : users) {
            updateFaceContent(user);
        }
        userRepository.saveAll(users);
    }

    //更新用户颜值相关内容
    public void updateFaceContent(UserDO user) {
        Integer[] faceValues;
        if (user.getGender().equals(CommonConst.boy)) {
            faceValues = AppConfigConst.getBoysFaceValueList();
        } else {
            faceValues = AppConfigConst.getGirlsFaceValueList();
        }
        //用户被查看，喜欢次数+1
       /* user.setSeeCount(user.getSeeCount() + 1);
        //根据用户的查看次数和喜欢次数，计算用户的颜值
        long faceValue = user.getLikeCount() * MatchConstants.FACE_VALUE_BASE_MULTIPLE / user.getSeeCount();
        user.setFaceValue((int) faceValue);
        //有了用户颜值
        Integer userFaceValue = user.getFaceValue();
        int faceValueLength = faceValues.length;
        //颜值从小到大排序的
        if (faceValues.length > 0) {
            //默认最后一名
            int faceRank = binary(faceValues, userFaceValue);
            Long setFaceRatio;
            if (faceRank >= faceValueLength) {
                user.setFaceRank(1);
                setFaceRatio = MatchConstants.FACE_VALUE_BASE_MULTIPLE;
            } else {
                user.setFaceRank(faceValueLength - faceRank);
                setFaceRatio = faceRank * MatchConstants.FACE_VALUE_BASE_MULTIPLE / faceValueLength;
            }
            user.setBaseFaceRatio(setFaceRatio.intValue());
            if (user.getVipFlag() != null && user.getVipFlag()) {
                //普通会员加20分
                setFaceRatio += MatchConstants.FACE_VALUE_VIP_APPEND_MULTIPLE;
            }
            //根据这个排名除以总男数得到百分比数
            //认证增加30分
            *//*if (user.isCertified()) {
                setFaceRatio += MatchConstants.FACE_VALUE_APPEND_MULTIPLE;
            }*//*
            //年会员加30分
            *//*if (user.getYearVipFlag() != null && user.getYearVipFlag()) {
                setFaceRatio += MatchConstants.FACE_VALUE_YEAR_VIP_APPEND_MULTIPLE;
            } else if (user.getVipFlag() != null && user.getVipFlag()) {
                //普通会员加20分
                setFaceRatio += MatchConstants.FACE_VALUE_VIP_APPEND_MULTIPLE;
            }*//*
            //100个清池币1颜值
            *//*if (user.getQcb() != null && user.getQcb() > 0) {
                setFaceRatio += user.getQcb() * MatchConstants.QCB_FACE_VALUE_RATIO;
            }*//*
            user.setFaceRatio(setFaceRatio.intValue());
        }*/
    }

    //## 标题二分法查找,返回插入点索引
    public static int binary(Integer[] arr, Integer n) {
        int low = 0;
        int high = arr.length - 1;
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;
            if (arr[mid].equals(n)) {
                return mid;
            } else if (arr[mid] > n) {
                high = mid - 1;
            } else if (arr[mid] < n) {
                low = mid + 1;
            }
        }
        return mid + 1;
    }
}
